<template>
  <div  class="wrapper">
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '15px' }" />
    <div style="height:200px">
      <FormPanel
        ref="from"
        :list="initForm"
        :cols="3"
        :formType="value.type"
        :labelWidth="130"
        :isSubmitBtn="false"
        :collapse="false"
        @formChange="changeHandle"
      />
    </div>
    <BreakSpace label="详细信息" :containerStyle="{ marginBottom: '15px' }" />

    <FilterTable
      height="500"
      ref="tableDetail"
      :columns="detailColumns"
      :isSelectColumn="isSelectColumn"
      :mergeCellMethod="arraySpanMethod"
      :isMemoryPagination="true"
      :rowstyles="rowstyles"
      :onSyncTableData="syncPjFun"
      :datakey="'records'"
      :isToperInfo="false"
      :isExportExcel2="true"
      exportFileName="pdi明细.xlsx"
      :onColumnsChange="detailColumns => (this.detailColumns = detailColumns)"
      columnsRef="jzySeries"
    >
    </FilterTable>

    <BaseDialog :visible.sync="visbleVehicle" title="车辆选择"
                destroyOnClose>
      <add-vehicle
        selectionType="single"
        @selectArr="selectVehicleFun"
        @closeDialog='visbleVehicle = false'></add-vehicle>
    </BaseDialog>

    <div class="dialogBottmView">
      <el-button @click="closeDialog('closeDialog')">返 回</el-button>
      <el-button  v-show="type!=='show'" :loading="loadingFlag" :disabled="saveFlag" @click="saveDialog('50101001')" type="primary">保 存</el-button>
      <el-button  v-show="type!=='show'" :loading="loadingFlag" :disabled="saveFlag" @click="saveDialog('50101002')" type="primary">处理完成</el-button>
    </div>
  </div>
</template>

<script>
import { getFileGroup } from '@/api/partsmanage/common/file';
import addVehicle from './addVehicle';
import { getCheckingGroup, postSave, getExistCheckingGroup } from '@/api/serviceass/pdimanage/meetingcar';
import { dictionary } from '@/utils/dictMixin';
export default {
  name: 'servicessbpdimanagestockinfo',
  mixins: [dictionary],
  components: {
    addVehicle
  },
  props:{
    value: {
      type: Object,
      data: Object,
      required: true,
    },
  },
  data() {
    this.saveData=null;
    return {
      startList:[],
      type: this.value.type,
      initForm : this.initFormFun(),
      detailColumns: this.creatHeaderDetailColumns(),
      isSelectColumn: false,
      visbleVehicle: false,
      formData: {},
      rowstyles: [],
      loadingFlag: false,
      id: '',
      jcid: '',
      vehicle: {},
      saveFlag: false
    }
  },
  created() {
    this.init(this.value.data)
  },
  methods: {
    init(data) {
      if(this.type==='edit'|| this.type==='show'){
        this.id = data.id
        this.jcid = data.fwjcid
        if (data.fwdjzt === 50101002) {
          this.saveFlag = true
          this.detailColumns.forEach(x => {
            if (x.dataIndex === 'fwjcjg' || x.dataIndex === 'fwwtms' || x.dataIndex === 'fwcljg') {
              x.editable = false
            }
          })
        }
        this.initForm.forEach(x => {
          x.initialValue = data[x.fieldName];
        });
        getExistCheckingGroup({ "id": this.id }).then(response => {
          var list = response.data.records
          if(response.resultCode === 200){
            this.$nextTick(()=>{
              this.$refs.tableDetail.EXECUTE_INSERT(list)
              this.startList=list
            })
          }
        })
        getFileGroup({ "xtdjid": this.id, "xtfjlx": "7" }).then(response => {
          var fileList = response.data.records
          this.initForm.forEach(x => {
            if (x.fieldName === 'wayFiles') {
              x.initialValue = fileList
            }
          })
        })
      } else {
        getCheckingGroup({ "fwjclx": '50091002' }).then(response => {
          var list = response.data.records
          list.forEach(x => {
            if (x.type === 'project') {
              x.fwjcjg = 50111001
              x.fwcljg = 50121001
            }
          })
          if(response.resultCode === 200){
            this.$nextTick(()=>{
              this.$refs.tableDetail.EXECUTE_INSERT(list)
              this.startList=list
            })
          }
        })
      }
    },
    initFormFun() {
      return [
        {
          type: 'SELECT',
          label: 'PDI类型',
          fieldName: 'fwdjlx',
          placeholder: '请选择',
          initialValue: 50091002,
          disabled: true,
          itemList: this.createDictList('5009'),
        },
        {
          type: 'INPUT',
          label: '车架号',
          fieldName: 'fwvinm',
          placeholder: '请选择',
          readonly: true,
          initialValue: '',
          rules: [
            {required: true, trigger: 'change', message: '请选择车辆'}
          ],
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.visbleVehicle = true}></el-button>
              </div>
            );
          },
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'fwchex',
          placeholder: '请输入',
          initialValue: '',
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'fwbiez',
          placeholder: '请输入',
          selfCols:3,
        },
        {
          selfCols: 3,
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'wayFiles',
          placeholder: '上传文件...',
          rules: [{ required: true, message: '请上传文件', trigger: 'change' }],
          // initialValue: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }],
          initialValue: '',
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 2,
            tipText: '（支持：PDF、RAR、JPG格式）'
          }
        },
        {
          type: 'INPUT',
          label: '电机编号',
          fieldName: 'fwfdjh',
          hidden:true,
          initialValue: ''
        },
      ]
    },
    creatHeaderDetailColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'indexnum',
          sorter: true
        },
        {
          title: '检查项目',
          dataIndex: 'fwjcxm',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '检查结果',
          dataIndex: 'fwjcjg',
          sorter: true,
          editable: true,
          editType: 'select',
          editRequired: true,
          placeholder: 50111001,
          editItems: this.createDictList('5011'),
          filter: true,
          filterType: 'checkbox',
          filterItems:this.createDictList('5011')
        },
        {
          title: '问题描述',
          dataIndex: 'fwwtms',
          sorter: true,
          editable: true,
          editType: 'input'
        },
        {
          title: '处理结果',
          dataIndex: 'fwcljg',
          sorter: true,
          editable: true,
          editType: 'select',
          editItems: this.createDictList('5012'),
          filter: true,
          filterType: 'checkbox',
          filterItems:this.createDictList('5012')
        },
      ]
    },
    changeHandle(val){
      this.saveData=val
    },
    syncPjFun(details, isOverdue){
      this.formData.details = details
      if (!details.length) return;
      details.forEach(x => {
        if (x.type == 'area') {
          this.rowstyles.push({ row: x, styles: { background: '#C4C4C4' } });
        }
      });
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (row.type === 'area' && columnIndex === 1) {
        return {
          rowspan: 1,
          colspan: 4
        };      // 跨列
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', {visible: false, type: type});
    },
    async saveDialog(val) {
      this.$refs.from.SUBMIT_FORM();
      if (this.formData.details.length < this.startList.length){
        this.$notify.error({title: '提示信息',message:'请先清空表格查询条件'});
      }else{
        if (this.saveData) {
          this.saveData.id = this.id
          this.saveData.detailList = this.formData.details
          this.saveData.fwdjzt = val
          this.saveData.fwjcid = this.jcid
          if (!this.id){
            this.saveData.fwfdjh = this.vehicle.fwfdjh
          }else{
            this.saveData.fwfdjh = this.value.data.fwfdjh
          }
          if (this.vehicle.fwvinm !== undefined && this.vehicle.fwvinm !== null && this.vehicle.fwvinm !== '') {
            this.saveData.fwjcid = this.vehicle.id
          }
          if (this.saveData.detailList === null || this.saveData.detailList === undefined || this.saveData.detailList === [] || this.saveData.detailList.length === 0) {
            this.$notify.error({title: '提示信息',message:'没有检查项目'||'保存失败!'});
            return false;
          }
          this.loadingFlag = true;
          console.info('保存的数据')
          console.info(this.saveData)
          let res=await postSave(this.saveData)
          if (res.resultCode === 200) {
            this.$notify.success({title: '提示信息',message:'保存成功!'});
            this.loadingFlag = false;
            this.closeDialog('refresh')
          } else {
            this.loadingFlag = true;
            this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
          }
        }
      }
    },
    /*选择车辆信息回调 */
    selectVehicleFun(arr) {
      this.vehicle = arr[0]
      this.visbleVehicle = false
      this.initForm.forEach(x => {
        if (x.fieldName === 'fwvinm') {
          x.initialValue = this.vehicle.fwvinm
        }
        if (x.fieldName === 'fwchex') {
          x.initialValue = this.vehicle.fwchex
        }
      })
    },
  }
}
</script>
